/*
 * Common API for all pages
 */
const REST_API_PREFIX="/symdb/";

function fnGetProductRestPrefix() {
	const urlParams = new URLSearchParams(window.location.search);
	let product = urlParams.get('product');
	let version = urlParams.get('version');

	if (!product) {
		product = "ohos_rk3568"; // Default product
		version = "3.2.6.5"; // Default version
	}
	return `${REST_API_PREFIX}products/${product}/${version}/`;
}

function redirectToDefaultProduct() {
	$.get(`${REST_API_PREFIX}products`, function (data, status) {
		const products = JSON.parse(data)["data"];
		if (products && products.length > 0) {
		    window.location = fnGetStaticHtmlUrl("modules", products[0][1], products[0][2]);
        }
	});
}

function fnGetStaticHtmlUrl(name, product, version, xargs = {}) {
    const urlParams = new URLSearchParams(window.location.search);
	const args = { ...xargs };

	if (product && version) {
		args["product"] = product;
		args["version"] = version;
	} else {
		args["product"] = urlParams.get('product');
		args["version"] = urlParams.get('version');
	}
	const query = new URLSearchParams(args).toString();
	return `/${name}.html?${query}`;
}

function fnGetAllItemsFilterUrl(name, xargs = {}) {
	const prefix = fnGetProductRestPrefix();
	const url =  `${prefix}${name}`;
    const urlParams = new URLSearchParams(window.location.search);
	const args = { ...xargs };

    urlParams.forEach((val, key) => {
        if (!["product", "version", "_"].includes(key)) {
			args[key] = val;
		}
    });

    const query = new URLSearchParams(args).toString();
	return query ? `${url}?${query}` : url;
}

function humanFileSize(size) {
    size = parseInt(size, 10);
    if (isNaN(size) || size === 0) return '0 B';
    const i = Math.floor(Math.log(size) / Math.log(1024));
    return `${(size / Math.pow(1024, i)).toFixed(2) * 1} ${['B', 'kB', 'MB', 'GB', 'TB'][i]}`;
}

// Initialize top-level menus and common elements
$(function() {
    const pages = {
		"modules": {"name": "模块列表"},
		"records": {"name": "内存信息"}
	};
    const file = window.location.pathname.split('/').pop() || 'modules.html';
	const currentPage = file.substring(0, file.indexOf(".html"));

    // Create main page navigation
    const pagesMenuHtml = Object.entries(pages).map(([key, val]) => {
        const isActive = (currentPage === key) ? ' active' : '';
        return `<li class="nav-item"><a href="${fnGetStaticHtmlUrl(key)}" class="nav-link${isActive}">${val.name}</a></li>`;
    }).join('\n');
	$("#pages_menu").html(pagesMenuHtml);

    // Create product selection dropdown
	$.get(`${REST_API_PREFIX}products`, function (data) {
		const products = JSON.parse(data)["data"];
        const urlParams = new URLSearchParams(window.location.search);
		let curProduct = urlParams.get('product');
		let curVersion = urlParams.get('version');

        if (!curProduct && products.length > 0) {
            curProduct = products[0][1];
            curVersion = products[0][2];
        }

        let menuHtml = `<button id="current_product_btn" class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown">${curProduct}/${curVersion}</button>`;
        menuHtml += '<ul class="dropdown-menu text-small">';

        const productsByName = {};
        products.forEach(p => {
            if (!productsByName[p[1]]) productsByName[p[1]] = [];
            productsByName[p[1]].push(p[2]);
        });

        for (const [productName, versions] of Object.entries(productsByName)) {
            menuHtml += `<li><a class="dropdown-item">${productName}&raquo;</a><ul class="dropdown-menu dropdown-submenu">`;
            versions.forEach(v => {
                menuHtml += `<li><a class="dropdown-item" href="${fnGetStaticHtmlUrl(currentPage, productName, v)}">${v}</a></li>`;
            });
            menuHtml += '</ul></li>';
        }
        menuHtml += '</ul>';
		$("#products_menu").html(menuHtml);
	});
});

const tableOptions = {
	"deps_dialog": {
		"title": "依赖关系列表",
		"buttons": [{ "id": "download_xml_deps", "name": "XML下载" }, { "id": "download_svg_deps", "name": "SVG下载" }, { "id": "download_png_deps", "name": "PNG下载" }, { "id": "download_dot_deps", "name": "GraphViz文件下载" }],
		"table": { "id": "depends", "cols": ["Id", "CallerId", "CalleeId", "调用模块", "被调用模块", "调用次数"] }
	},
	"help_info_dialog": {
		"title": "帮助信息",
		"extra": { "class": "help_modal", "style": "transform: translateX(-50%) translateY(-50%)" },
		"wrapper": { "id": "help_info_img", "type": "img" }
	},
	"module_dialog": {
		"title": "模块详细信息",
		"wrapper": { "id": "accordion", "type": "div" }
	},
	"callinfo_dialog": {
		"title": "调用详情",
		"buttons": [{ "id": "download_xml_callinfo", "name": "XML下载" }],
		"table": { "id": "callinfo_table", "cols": ["调用者", "提供者", "函数名", "类型", "段名称"] }
	},
	"symbol_dialog": {
		"title": "符号信息",
		"buttons": [{ "id": "download_xml_symbols", "name": "XML下载" }],
		"table": { "id": "symbol_table", "cols": ["调用者", "提供者", "函数名", "类型", "段名称"] }
	},
    "processes_dialog": {
		"title": "进程信息",
		"buttons": [{ "id": "download_xml_processes", "name": "XML下载" }],
		"table": { "id": "processes_table", "cols": ["id", "record_id", "record_name", "pid", "ppid", "command", "threads", "rss", "vsize", "region_types", "vmmap_regions", "vmmap_vsize", "vmmap_resident", "vmmap_dirty", "vmmap_swap", "footprint_Dirty", "footprint_Clean", "footprint_Reclaimable", "footprint_Regions", "cpu", "state", "priority", "nice", "wq"] }
	},
	"processes_by_name_dialog": {
		"title": "进程内存变化",
		"buttons": [{ "id": "download_xml_processes", "name": "XML下载" }],
		"table": { "id": "processes_by_name_table", "cols": ["id", "record_id", "record_name", "pid", "ppid", "command", "threads", "rss", "vsize", "region_types", "vmmap_regions", "vmmap_vsize", "vmmap_resident", "vmmap_dirty", "vmmap_swap", "footprint_Dirty", "footprint_Clean", "footprint_Reclaimable", "footprint_Regions", "cpu", "state", "priority", "nice", "wq"] }
	},
	"region_types_dialog": {
		"title": "内存页分类信息",
		"buttons": [{ "id": "download_xml_region_types", "name": "XML下载" }],
		"table": { "id": "region_types_table", "cols": ["id", "record_id", "processes", "record_name", "name", "regions", "vsize", "resident", "dirty", "swap"] }
	},
	"region_details_dialog": {
		"title": "内存页详细信息",
		"buttons": [{ "id": "download_xml_region_details", "name": "XML下载" }],
		"table": { "id": "region_details_table", "cols": ["id", "record_id", "process_id", "record_name", "command", "type", "addr", "ugo", "sharemode", "purge", "detail", "vsize", "resident", "dirty", "swap"] }
	}
};

function _createDialogHeader(dialogId) {
    return `
        <div class="modal-header">
            <h5 class="modal-title">${tableOptions[dialogId]["title"]}</h5>
            <button type="button" class="close" data-dismiss="dialog" aria-label="Close" id="${dialogId}_close_btn" value="${dialogId}">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    `;
}

function _createDialogButtons(dialogId) {
	if (!("buttons" in tableOptions[dialogId])) {
		return "";
	}
	const buttonsHtml = tableOptions[dialogId]["buttons"].map(btn => 
		`<button type="button" id="${btn.id}" class="btn btn-sm btn-outline-secondary">${btn.name}</button>`
	).join('\n');

	return `
		<div class="btn-group me-2 float-end">
			${buttonsHtml}
		</div>
	`;
}

function _createDialogTables(dialogId) {
	if (!("table" in tableOptions[dialogId])) {
		return "";
	}
	const tableInfo = tableOptions[dialogId]["table"];
	const headers = tableInfo["cols"].map(th => `<th class="show_in_line">${th}</th>`).join('\n');

	return `
		<table cellpadding="0" cellspacing="0" border="0" class="display" id="${tableInfo.id}">
			<thead>
				<tr>
					${headers}
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
	`;
}

function _createWrapperBlock(dialogId) {
	if (!("wrapper" in tableOptions[dialogId])) {
		return "";
	}
	const wrapper = tableOptions[dialogId]["wrapper"];
	return `<${wrapper.type} id="${wrapper.id}">`;
}

function _createDialogDiv(dialogId) {
	if (!("extra" in tableOptions[dialogId])) {
		return '<div class="modal-dialog modal-lg" role="document"></div>';
	}
	const extra = tableOptions[dialogId]["extra"];
	const style = extra.style ? `style="${extra.style}"` : '';
	const extraClass = extra.class ? ` ${extra.class}` : '';

	return `<div class="modal-dialog modal-lg${extraClass}" role="document" ${style}>`;
}

function createDialogWithTable(dialogId) {
	if (!(dialogId in tableOptions)) {
		return;
	}

	const content = `
		${_createDialogDiv(dialogId)}
			<div class="modal-content">
				${_createDialogHeader(dialogId)}
				<div class="modal-body">
					${_createWrapperBlock(dialogId)}
					${_createDialogButtons(dialogId)}
					${_createDialogTables(dialogId)}
				</div>
				<div class="modal-footer"></div>
			</div>
		</div>
	`;

	$("#"+dialogId).html(content);

	$("#"+dialogId+"_close_btn").click(function(evt) {
		var dialogId = $(evt.target).parent().val();
		$("#"+dialogId).modal("hide");
	});
}

function fnArgsToURI(args) {
	var str = [];
	for(var p in args) {
		str.push(encodeURIComponent(p) + "=" + encodeURIComponent(args[p]));
	}
	return str.join("&");
}
